package cn.edu.swu.bc.servlet;

import cn.edu.swu.bc.filter.AuthFilter;
import cn.edu.swu.bc.utils.JsonUtils;
import cn.edu.swu.bc.utils.DBUtils;
import cn.edu.swu.bc.entity.Blog;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.sql.SQLException;
import java.util.List;

public class GetBlogsServlet extends HttpServlet {

    private static final long serialVersionUID = 119812548834340L;

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        this.doPost(request, response);
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int page = Integer.parseInt(request.getParameter("page"));
        int id = Integer.parseInt(request.getParameter("user_id"));
        if (id == -1)//id为-1访问自己的博客为0访问所以博客为固定id访问固定id的博客
            id = (Integer) request.getSession().getAttribute(AuthFilter.USER_ID);
        try {
            List<Blog> blogs;
            int blogsNum;
            //获取博客的信息
            blogs = DBUtils.getBlogs(id, page);
            if (id != 0)//id为0则查询所以博客
                blogsNum = DBUtils.getBlogsNumber(id);//获取博客的数量
            else
                blogsNum = DBUtils.getBlogsNumber();
            int pageNum;

            if (blogsNum % 5 == 0)
                pageNum = blogsNum / 5;
            else
                pageNum = blogsNum / 5 + 1;
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            Writer writer = response.getWriter();
            //打包成json数据
            writer.write(JsonUtils.blogToJson(blogs, pageNum, request));
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
